//
//  UserCenterController.m
//  HappyBaby
//
//  Created by 华哥 on 15/12/1.
//  Copyright © 2015年 华哥. All rights reserved.
//

#import "UserCenterController.h"
#import "Define.h"
#import "UserCenterCell.h"
#import "UserListModel.h"
#import <BmobSDK/Bmob.h>
#import <BmobSDK/BmobProFile.h>
#import "RegularValidate.h"

@interface UserCenterController () <UITextFieldDelegate, UITableViewDataSource, UITableViewDelegate,  UIImagePickerControllerDelegate, UINavigationControllerDelegate>

@property (nonatomic, strong) UIImageView *userheadImage;
@property (nonatomic, strong) UITextField *usernameLabel;
@property (nonatomic, strong) UITextField *userNickName;
@property (nonatomic, strong) UITextField *userPhone;
@property (nonatomic, strong) UITextField *userEmail;

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UserListModel *userModel;

@property (nonatomic, assign) BOOL isEditing;
@property (nonatomic, strong) NSMutableArray *cellArray;
@property (nonatomic, strong) UIButton *logOut;
@property (nonatomic, copy) NSString *nowTime;
@property (nonatomic, copy) NSString *userheadImagePath;

@end

static NSString *cellIndentifier = @"cell";
@implementation UserCenterController

- (void)viewDidLoad {
    [super viewDidLoad];
   
    
    [self achiveCurrentUser];
    [self createView];
    
    
    self.navigationController.navigationBar.translucent = NO;
    
    UIBarButtonItem *barButton = [[UIBarButtonItem alloc]initWithTitle:@"修改" style:UIBarButtonItemStylePlain target:self action:@selector(barButton:)];
    self.navigationItem.rightBarButtonItem = barButton;
    
    self.cellArray = [NSMutableArray array];
    
    self.logOut = [UIButton buttonWithType:UIButtonTypeCustom];
    self.logOut.frame = CGRectMake((kScreenWidth - 80) / 2, 400, 80, 30);
    self.logOut.backgroundColor = [UIColor redColor];
    self.logOut.layer.cornerRadius = 15;
    [self.logOut setTitle:@"注销登录" forState:UIControlStateNormal];
    [self.logOut setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.logOut addTarget:self action:@selector(logOutAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_logOut];
}

- (void)createView
{
    self.view.backgroundColor = [UIColor whiteColor];
    self.userheadImage = [[UIImageView alloc]initWithFrame:CGRectMake((kScreenWidth - 50) / 2, 20, 80, 80)];
    self.userheadImage.layer.cornerRadius = 40;
    self.userheadImage.layer.masksToBounds = YES;
    self.userheadImage.backgroundColor = [UIColor redColor];
    UITapGestureRecognizer *userheadImageTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(userheadImageTapAction)];
    [self.userheadImage addGestureRecognizer:userheadImageTap];
    [self.view addSubview:_userheadImage];
    
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 100, kScreenWidth, 300) style:UITableViewStyleGrouped];
    [self.tableView registerClass:[UserCenterCell class] forCellReuseIdentifier:cellIndentifier];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.separatorStyle = NO;
    self.tableView.bounces = NO;
    [self.view addSubview:_tableView];
}

#pragma mark -------------------- tableView设置 ---------------------------
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 4;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UserCenterCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIndentifier forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.textField.userInteractionEnabled = NO;
    switch (indexPath.row)
    {
        case 0:
            cell.label.text = @"昵称:";
            cell.textField.placeholder = self.userModel.userNickName;
            break;
            
        case 1:
            cell.label.text = @"用户名:";
            cell.textField.placeholder = self.userModel.username;
            break;
        case 2:
            cell.label.text = @"电话:";
            cell.textField.placeholder = self.userModel.userPhone;
            break;
        case 3:
            cell.label.text = @"Email:";
            cell.textField.placeholder = self.userModel.userEmail;
            break;
    }
    return cell;
}

#pragma mark ------------------- 获取当前用户信息 ------------------------
- (void)achiveCurrentUser
{
    self.userModel = [[UserListModel alloc]init];
    
    
    BmobUser *currentUser = [BmobUser getCurrentUser];
    self.userModel.username = currentUser.username;
    BmobFile *userheadFile = [currentUser objectForKey:@"userheadImage"];
    self.userModel.userheadImage = userheadFile.url;
    self.userModel.userEmail = [currentUser objectForKey:@"email"];
    self.userModel.userPhone = [currentUser objectForKey:@"mobilePhoneNumbel"];
    self.userModel.userNickName = [currentUser objectForKey:@"nickname"];
}

#pragma mark --------------  点击barButton执行的方法 -------------------------
- (void)barButton:(UIBarButtonItem *)barButton
{
    if (self.isEditing == NO)
    {
        for (UserCenterCell *cell in self.tableView.visibleCells)
        {
            cell.textField.userInteractionEnabled = YES;
            self.userheadImage.userInteractionEnabled = YES;
        }
        [barButton setTitle:@"保存"];
    }
    else
    {
        self.userheadImage.userInteractionEnabled = NO;
        BmobUser *bUser = [BmobUser getCurrentUser];
        for (UserCenterCell *cell in self.tableView.visibleCells)
        {
            [self.cellArray addObject:cell];
        }
        
        for (int i = 0; i < self.cellArray.count; i++)
        {
            UserCenterCell *cell = self.cellArray[i];
            
            switch (i)
            {
                case 0:
                    if (cell.textField.text.length != 0)
                    {
                         [bUser setObject:cell.textField.text forKey:@"nickname"];
                    }
                    break;
                case 1:
                    if (cell.textField.text.length != 0)
                    {
                        bUser.username = cell.textField.text;
                    }
                    break;
                case 2:
                    if (cell.textField.text.length != 0)
                    {
                        if ([RegularValidate validatePhone:cell.textField.text])
                        {
                            [bUser setObject:cell.textField.text forKey:@"mobilePhoneNumber"];
                        }
                        else
                        {
                            UIAlertView *alterView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"电话格式不正确" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                            [alterView show];
                            return;
                        }
                    }
                    break;
                case 3:
                    if (cell.textField.text.length != 0)
                    {
                        if ([RegularValidate validateEmail:cell.textField.text])
                        {
                            [bUser setObject:cell.textField.text forKey:@"email"];
                        }
                        else
                        {
                            UIAlertView *alterView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"邮箱格式不正确" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                            [alterView show];
                            return;
                        }
                    }
                    break;
            }
            cell.textField.userInteractionEnabled = NO;
        }
        
        if (self.userheadImagePath.length != 0)
        {
            [BmobProFile uploadFileWithPath:self.userheadImagePath block:^(BOOL isSuccessful, NSError *error, NSString *filename, NSString *url, BmobFile *file) {
                [bUser setObject:file forKey:@"userheadImage"];
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self.tableView reloadData];
                    [bUser updateInBackground];
                });
            } progress:^(CGFloat progress) {
                NSLog(@"%f",progress);
            }];
        }
        
        [bUser updateInBackgroundWithResultBlock:^(BOOL isSuccessful, NSError *error) {
            if (isSuccessful)
            {
                NSLog(@"修改信息成功");
                UIAlertView *alterView = [[UIAlertView alloc]initWithTitle:@"恭喜" message:@"修改成功" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                [alterView show];
            }
            else
            {
                NSLog(@"修改信息失败");
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.tableView reloadData];
                [barButton setTitle:@"修改"];
            });
        }];
    }
    _isEditing = !_isEditing;
}

#pragma mark ------------------- 调用系统图库 为Image附图片 -----------------------------
- (void)userheadImageTapAction
{
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeSavedPhotosAlbum]) {
        //NSLog(@"打开相册成功");
        UIImagePickerController *picker = [[UIImagePickerController alloc]init];
        picker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
        //  是否允许编辑
        picker.allowsEditing = YES;
        //  设置代理，自动去调用代理方法
        //  需要遵守UINavigationControllerDelegate和UIImagePickerControllerDelegate协议
        picker.delegate = self;
        [self presentViewController:picker animated:YES completion:nil];
    }
    else
    {
        NSLog(@"打开相册失败");
    }
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    NSLog(@"ok");
    //  1.将选中的图片赋值给imageView
    //  通过字典的key值来取出对应的value值，value就是选中的图片
    UIImage *image= [info objectForKey:@"UIImagePickerControllerOriginalImage"];
    if (picker.sourceType == UIImagePickerControllerSourceTypeCamera)
    {
        //  将某一张图片存到相册中
        UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
    }
    CGSize imageSize = image.size;
    imageSize.height = 256;
    imageSize.width = 256;
    image = [self imageWithImage:image scaledToSize:imageSize];
    //给上传图片区域附上图片
    self.userheadImage.image = [info objectForKey:UIImagePickerControllerOriginalImage];
    
    //获取时间来命名图片
    NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
    NSTimeInterval a=[dat timeIntervalSince1970]*1000;
    self.nowTime = [NSString stringWithFormat:@"%f", a];
    NSLog(@"nowTime ==== %@", self.nowTime);
    [self saveImage:image WithName:[self.nowTime stringByAppendingString:@".jpg"]];
    
    //  2.将本界面模态回去，即dismiss
    [self dismissViewControllerAnimated:YES completion:nil];
}

//压缩图片封装方法
-(UIImage*)imageWithImage:(UIImage*)image scaledToSize:(CGSize)newSize
{
    // Create a graphics image context
    UIGraphicsBeginImageContext(newSize);
    
    // Tell the old image to draw in this new context, with the desired
    // new size
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    
    // Get the new image from the context
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    
    // End the context
    UIGraphicsEndImageContext();
    
    // Return the new image.
    return newImage;
}

- (void)saveImage:(UIImage *)tempImage WithName:(NSString *)imageName
{
    NSData* imageData = UIImagePNGRepresentation(tempImage);
    NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString* documentsDirectory = [paths objectAtIndex:0];
    // Now we get the full path to the file
    NSString* fullPathToFile = [documentsDirectory stringByAppendingPathComponent:imageName];
    // and then we write it out
    [imageData writeToFile:fullPathToFile atomically:NO];
    self.userheadImagePath = fullPathToFile;
}

- (NSString *)documentFolderPath
{
    NSLog(@"documentFolderPath ==== %@",[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"]);
    return [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
}

#pragma mark ---------------------- 注销登录 ------------------------------
- (void)logOutAction
{
    BmobUser *currentUser = [BmobUser getCurrentUser];
    currentUser = nil;
    [[NSUserDefaults standardUserDefaults]setBool:NO forKey:@"isLogin"];
}

















@end
